/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package jpao.benchmark.instrument;

import jpao.benchmark.metric.Metric;
import jpao.benchmark.metric.Unit;

/**
 * This class is an instrument designed for measuring elapsed time.<br>
 * This class is <b>not</b> thread-safe.<br><br>
 * 
 * Usage:<br><br>
 * <code>
 * StopWatch stopWatch = new StopWatch();<br>
 * stopWatch.startMeasuring();<br>
 * // compute something<br>
 * stopWatch.stopMeasuring();<br>
 * Metric elapsedTime = stopWatch.getMetric();<br>
 * </code>
 * @version 1.0
 * @author julien.paoletti@gmail.com
 * @since 1.0
 */
public class StopWatch implements TimeInstrument {

    private long startTime;
    private long elapsedTime = 0;
    private boolean isMeasuring = false;

    public void startMeasuring() {
        if (isMeasuring) {
            throw new IllegalStateException("This StopWatch is already measuring ..");
        }
        isMeasuring = true;
        startTime = System.nanoTime();
    }

    public void stopMeasuring() {
        if (!isMeasuring) {
            throw new IllegalStateException("This StopWatch needs to start measuring before stopping ..");
        }
        elapsedTime = System.nanoTime() - startTime;
        isMeasuring = false;
    }

    public Metric getMetric() {
        Metric time = new Metric();
        time.setMeasure(elapsedTime);
        time.setUnit(Unit.NANOSECOND_UNIT);
        return time;
    }
}
